//mongoose操作数据库入口文件
const mongoose = require('mongoose')
const { uri, options } = require('./mongodb.config')
const fs = require('fs')
const { Static_Data, Document, top_view, YiriDoc, WeChat_Document } = require('./schema')

//创建连接
mongoose.connect(uri, options)
    .then(() => {
        console.log('连接成功')
    }).catch(err => {
        console.log(err)
        console.log('连接失败')
    })

//设置查询静态数据方法
function getStaticData(query) {
    return new Promise((reslove, reject) => {
        Static_Data.find(query, { _id: 0 }).then(res => reslove(res)).catch(err => reject(err))
    })
}

//一日文章
async function writeYiriDoc(data) {
    return new Promise(async (reslove, reject) => {
        YiriDoc.create(data, (err, res) => {
            if (err) {
                reject({ errMsg: err })
            }
            else {
                console.log('添加成功!')
                reslove({ errMsg: 'ok' })
            }
        })
    })
}

//保存微信公众号文章文章
async function writeWeChatDoc(data) {
    return new Promise(async (reslove, reject) => {
        WeChat_Document.findOne({ name: data.name }, async (err, res) => {
            if (err) {
                reject({ errMsg: err })
            }
            else {

                if (res) {
                    console.log('查询到有同名文档')
                    console.log(res)
                    reslove(res)
                } else {
                    console.log('未查询到有同名文档')
                    const num = await WeChat_Document.find({}).count() + 1

                    data.id = 'WX-' + num.toString().padStart(3, '0')
                    data.to = '/news/' + data.id
                    WeChat_Document.create({ ...data }, (err, res) => {
                        if (err) {
                            reject({ errMsg: err })
                        }
                        else {
                            console.log('添加成功!')
                            reslove(data)
                        }
                    })
                }
            }
        })
    })
}

//获得主题首页的方法
async function getTopicHome(id) {
    let topic = ''
    if (id === 'shimian') {
        topic = 'shimian'
    } else if (id === 'xuanyun') {
        topic = 'xuanyun'
    } else if (id === 'pifu') {
        topic = 'pifu'
    }

    const firstTopic = await Document.find({ classify: topic, topic: 'firstTopic' }, { _id: 0, __v: 0 })
    const secondTopic = await Document.find({ classify: topic, topic: 'secondTopic' }, { _id: 0, __v: 0 })
    const thirdTopic = await Document.find({ classify: topic, topic: 'thirdTopic' }, { _id: 0, __v: 0 })
    const lastTopic = await Document.find({ classify: topic, topic: 'lastTopic' }, { _id: 0, __v: 0 })
    console.log(id)
    const topView = await top_view.findOne({ id }, { _id: 0, id: 0 })
    console.log(topView)

    return new Promise(async (reslove, reject) => {
        Static_Data.findOne({ page: 'documentHome' }, { _id: 0 }).then(res => {
            console.log(res.name)
            const topic = {
                firstTopic: { title: res.firstTopic.title, topics: firstTopic },
                secondTopic: { title: res.secondTopic.title, topics: secondTopic },
                thirdTopic: { title: res.thirdTopic.title, topics: thirdTopic },
                lastTopic: { title: res.lastTopic.title, topics: lastTopic },
                topView
            }
            reslove({ ...topic })
        }).catch(err => reject(err))
    })
}

//添加文档方法
function writeDocument(data) {
    return new Promise((reslove, reject) => {
        Document.findOne({ id: data.id }, { _id: 0 }).then(res => {
            console.log(res + '\t\n============')
            if (!res) {
                console.log('创建新的文档')
                Document.create(data, (err, res) => {
                    if (err) {
                        reject({ errMsg: err })
                    }
                    else {
                        console.log('添加成功!')
                        reslove({ errMsg: 'ok' })
                    }
                })
            } else {
                //修改方法
                console.log('修改id为' + res.id + '的文档')
                Document.updateOne({ id: data.id }, data).then(res1 => reslove(res1)).catch(err1 => reject(err1))
            }
        })
    })
}

//修改方法
function updateDocument(id, data) {

    return new Promise(async (reslove, reject) => {
        //创建连接
        await mongoose.connect(uri, options)


        const res = await Document.updateOne({ id }, data)
        reslove(res)
        mongoose.disconnect()
    })
}

async function getTopicDetail(params) {
    //获取目录 
    query = {
        condition: { classify: params.topic },
        limit: 999,
        skip: 0
    }
    query.condition = { id: params.id }
    const result = await getDocument(query)

    let context = []
    if (params.topic === 'shimian') {
        try {
            const res = fs.readFileSync('./shimianContext.json')
            console.log('获取目录')
            context = JSON.parse(res)
        } catch (error) {
            console.log('新建目录')
            context = [
                {
                    name: (document.filter(v => v.chapter === '常识篇'))[0].chapter,
                    titles: (document.filter(v => v.chapter === '常识篇')).map(v => v.title),
                    to: (document.filter(v => v.chapter === '常识篇')).map(v => v.to),
                    id: (document.filter(v => v.chapter === '常识篇')).map(v => v.id)
                },
                {
                    name: (document.filter(v => v.chapter === '病因篇'))[0].chapter,
                    titles: (document.filter(v => v.chapter === '病因篇')).map(v => v.title),
                    to: (document.filter(v => v.chapter === '病因篇')).map(v => v.to),
                    id: (document.filter(v => v.chapter === '病因篇')).map(v => v.id)
                },
                {
                    name: (document.filter(v => v.chapter === '症状篇'))[0].chapter,
                    titles: (document.filter(v => v.chapter === '症状篇')).map(v => v.title),
                    to: (document.filter(v => v.chapter === '症状篇')).map(v => v.to),
                    id: (document.filter(v => v.chapter === '症状篇')).map(v => v.id)
                },
                {
                    name: (document.filter(v => v.chapter === '诊断篇'))[0].chapter,
                    titles: (document.filter(v => v.chapter === '诊断篇')).map(v => v.title),
                    to: (document.filter(v => v.chapter === '诊断篇')).map(v => v.to),
                    id: (document.filter(v => v.chapter === '诊断篇')).map(v => v.id)
                },
                {
                    name: (document.filter(v => v.chapter === '治疗篇'))[0].chapter,
                    titles: (document.filter(v => v.chapter === '治疗篇')).map(v => v.title),
                    to: (document.filter(v => v.chapter === '治疗篇')).map(v => v.to),
                    id: (document.filter(v => v.chapter === '治疗篇')).map(v => v.id)
                },
                {
                    name: (document.filter(v => v.chapter === '预防保健篇'))[0].chapter,
                    titles: (document.filter(v => v.chapter === '预防保健篇')).map(v => v.title),
                    to: (document.filter(v => v.chapter === '预防保健篇')).map(v => v.to),
                    id: (document.filter(v => v.chapter === '预防保健篇')).map(v => v.id)
                }
            ]
            fs.writeFileSync('./shimianContext.json', JSON.stringify(context))
        }
        result.img = '/shimianImg.png'
    } else if (params.topic === 'pifu') {
        try {
            const res = fs.readFileSync('./pifuContext.json')
            console.log('获取目录')
            context = JSON.parse(res)

        } catch (error) {
            console.log('新建目录')
            context = [
                {
                    name: (document.filter(v => v.chapter === '常识篇'))[0].chapter,
                    titles: (document.filter(v => v.chapter === '常识篇')).map(v => v.title),
                    to: (document.filter(v => v.chapter === '常识篇')).map(v => v.to),
                    id: (document.filter(v => v.chapter === '常识篇')).map(v => v.id)
                },
                {
                    name: (document.filter(v => v.chapter === '常见疾病篇'))[0].chapter,
                    titles: (document.filter(v => v.chapter === '常见疾病篇')).map(v => v.title),
                    to: (document.filter(v => v.chapter === '常见疾病篇')).map(v => v.to),
                    id: (document.filter(v => v.chapter === '常见疾病篇')).map(v => v.id)
                },

            ]
            fs.writeFileSync('./pifuContext.json', JSON.stringify(context))
        }
        result.img = '/pifuImg.png'
    } else {
        try {
            const res = fs.readFileSync('./xuanyunContext.json')
            console.log('获取目录')
            context = JSON.parse(res)

        } catch (error) {
            console.log('新建目录')
            context = [{
                name: (document.filter(v => v.chapter.indexOf('第一章') >= 0))[0].chapter,
                titles: (document.filter(v => v.chapter.indexOf('第一章') >= 0)).map(v => v.title),
                to: (document.filter(v => v.chapter.indexOf('第一章') >= 0)).map(v => v.to),
                id: (document.filter(v => v.chapter.indexOf('第一章') >= 0)).map(v => v.id)
            },
            {
                name: (document.filter(v => v.chapter.indexOf('第二章') >= 0))[0].chapter,
                titles: (document.filter(v => v.chapter.indexOf('第二章') >= 0)).map(v => v.title),
                to: (document.filter(v => v.chapter.indexOf('第二章') >= 0)).map(v => v.to),
                id: (document.filter(v => v.chapter.indexOf('第二章') >= 0)).map(v => v.id)
            },
            {
                name: (document.filter(v => v.chapter.indexOf('第三章') >= 0))[0].chapter,
                titles: (document.filter(v => v.chapter.indexOf('第三章') >= 0)).map(v => v.title),
                to: (document.filter(v => v.chapter.indexOf('第三章') >= 0)).map(v => v.to),
                id: (document.filter(v => v.chapter.indexOf('第三章') >= 0)).map(v => v.id)
            },
            {
                name: (document.filter(v => v.chapter.indexOf('第四章') >= 0))[0].chapter,
                titles: (document.filter(v => v.chapter.indexOf('第四章') >= 0)).map(v => v.title),
                to: (document.filter(v => v.chapter.indexOf('第四章') >= 0)).map(v => v.to),
                id: (document.filter(v => v.chapter.indexOf('第四章') >= 0)).map(v => v.id)
            },
            {
                name: (document.filter(v => v.chapter.indexOf('第五章') >= 0))[0].chapter,
                titles: (document.filter(v => v.chapter.indexOf('第五章') >= 0)).map(v => v.title),
                to: (document.filter(v => v.chapter.indexOf('第五章') >= 0)).map(v => v.to),
                id: (document.filter(v => v.chapter.indexOf('第五章') >= 0)).map(v => v.id)
            },
            {
                name: (document.filter(v => v.chapter.indexOf('第六章') >= 0))[0].chapter,
                titles: (document.filter(v => v.chapter.indexOf('第六章') >= 0)).map(v => v.title),
                to: (document.filter(v => v.chapter.indexOf('第六章') >= 0)).map(v => v.to),
                id: (document.filter(v => v.chapter.indexOf('第六章') >= 0)).map(v => v.id)
            },
            {
                name: (document.filter(v => v.chapter.indexOf('第七章') >= 0))[0].chapter,
                titles: (document.filter(v => v.chapter.indexOf('第七章') >= 0)).map(v => v.title),
                to: (document.filter(v => v.chapter.indexOf('第七章') >= 0)).map(v => v.to),
                id: (document.filter(v => v.chapter.indexOf('第七章') >= 0)).map(v => v.id)
            },
            {
                name: (document.filter(v => v.chapter.indexOf('第八章') >= 0))[0].chapter,
                titles: (document.filter(v => v.chapter.indexOf('第八章') >= 0)).map(v => v.title),
                to: (document.filter(v => v.chapter.indexOf('第八章') >= 0)).map(v => v.to),
                id: (document.filter(v => v.chapter.indexOf('第八章') >= 0)).map(v => v.id)
            },
            {
                name: (document.filter(v => v.chapter.indexOf('第九章') >= 0))[0].chapter,
                titles: (document.filter(v => v.chapter.indexOf('第九章') >= 0)).map(v => v.title),
                to: (document.filter(v => v.chapter.indexOf('第九章') >= 0)).map(v => v.to),
                id: (document.filter(v => v.chapter.indexOf('第九章') >= 0)).map(v => v.id)
            },
            {
                name: (document.filter(v => v.chapter.indexOf('第十章') >= 0))[0].chapter,
                titles: (document.filter(v => v.chapter.indexOf('第十章') >= 0)).map(v => v.title),
                to: (document.filter(v => v.chapter.indexOf('第十章') >= 0)).map(v => v.to),
                id: (document.filter(v => v.chapter.indexOf('第十章') >= 0)).map(v => v.id)
            },
            {
                name: (document.filter(v => v.chapter.indexOf('第十一章') >= 0))[0].chapter,
                titles: (document.filter(v => v.chapter.indexOf('第十一章') >= 0)).map(v => v.title),
                to: (document.filter(v => v.chapter.indexOf('第十一章') >= 0)).map(v => v.to),
                id: (document.filter(v => v.chapter.indexOf('第十一章') >= 0)).map(v => v.id)
            },
            {
                name: (document.filter(v => v.chapter.indexOf('第十二章') >= 0))[0].chapter,
                titles: (document.filter(v => v.chapter.indexOf('第十二章') >= 0)).map(v => v.title),
                to: (document.filter(v => v.chapter.indexOf('第十二章') >= 0)).map(v => v.to),
                id: (document.filter(v => v.chapter.indexOf('第十二章') >= 0)).map(v => v.id)
            },
            {
                name: (document.filter(v => v.chapter.indexOf('第十三章') >= 0))[0].chapter,
                titles: (document.filter(v => v.chapter.indexOf('第十三章') >= 0)).map(v => v.title),
                to: (document.filter(v => v.chapter.indexOf('第十三章') >= 0)).map(v => v.to),
                id: (document.filter(v => v.chapter.indexOf('第十三章') >= 0)).map(v => v.id)
            },
            {
                name: (document.filter(v => v.chapter.indexOf('第十四章') >= 0))[0].chapter,
                titles: (document.filter(v => v.chapter.indexOf('第十四章') >= 0)).map(v => v.title),
                to: (document.filter(v => v.chapter.indexOf('第十四章') >= 0)).map(v => v.to),
                id: (document.filter(v => v.chapter.indexOf('第十四章') >= 0)).map(v => v.id)
            },
            {
                name: (document.filter(v => v.chapter.indexOf('第十五章') >= 0))[0].chapter,
                titles: (document.filter(v => v.chapter.indexOf('第十五章') >= 0)).map(v => v.title),
                to: (document.filter(v => v.chapter.indexOf('第十五章') >= 0)).map(v => v.to),
                id: (document.filter(v => v.chapter.indexOf('第十五章') >= 0)).map(v => v.id)
            },
            {
                name: (document.filter(v => v.chapter.indexOf('第十六章') >= 0))[0].chapter,
                titles: (document.filter(v => v.chapter.indexOf('第十六章') >= 0)).map(v => v.title),
                to: (document.filter(v => v.chapter.indexOf('第十六章') >= 0)).map(v => v.to),
                id: (document.filter(v => v.chapter.indexOf('第十六章') >= 0)).map(v => v.id)
            },
            ]
            fs.writeFileSync('./xuanyunContext.json', JSON.stringify(context))
        }
        result.img = '/xuanyunImg.png'
    }


    return new Promise(async (reslove, reject) => {
        reslove({ context, document: result.res[0], totalNum: result.totalNum, img: result.img })
    })
}

//获取文档 
function getDocument(query) {
    console.log(query)
    return new Promise(async (reslove, reject) => {
        const totalNum = await Document.find({}).count()
        Document.find(query.condition, { _id: 0, __v: 0, image: 0 }, { limit: query.limit, skip: query.skip, sort: { id: -1 } }).then(res => reslove({ res, totalNum })).catch(err => reject(err))
    })
}


function getNews(query) {
    return new Promise(async (reslove, reject) => {

        WeChat_Document.find(query.condition, { _id: 0, __v: 0 }, {
            limit: query.limit, skip: query.skip, sort: { id: -1 }
        }).then(res => {
            reslove(res)
        }).catch(err => reject(err))
    })
}

module.exports = {
    getStaticData,
    writeDocument,
    getDocument,
    getTopicHome,
    updateDocument,
    writeYiriDoc,
    writeWeChatDoc,
    getNews,
    getTopicDetail
}